Constructor (object-oriented programming)

Programming language comparisons
General comparison
Basic syntax
Basic instructions
Arrays
Associative arrays
String operations
String functions
List comprehension
Object-oriented programming
Object-oriented constructors
Database access
Database RDBMS

Evaluation strategy
List of "hello world" programs

ALGOL 58's influence on ALGOL 60
ALGOL 60: Comparisons with other languages
Comparison of ALGOL 68 and C++
ALGOL 68: Comparisons with other languages
Compatibility of C and C++
Comparison of Pascal and Borland Delphi
Comparison of Object Pascal and C
Comparison of Pascal and C
Comparison of Java and C++
Comparison of C# and Java
Comparison of C# and Visual Basic .NET

In object-oriented programming, a constructor (sometimes shortened to ctor) in a class is a special type of subroutine called at the creation of an object. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created. It is called a constructor because it constructs the values of data members of the class.

A constructor resembles an instance method, but it differs from a method in that it never has an explicit return-type, it is not inherited (though many languages provide access to the superclass's constructor, for example through the super keyword in Java), and it usually has different rules for scope modifiers. Constructors are often distinguished by having the same name as the declaring class. They have the task of initializing the object's data members and of establishing the invariant of the class, failing if the invariant isn't valid. A properly written constructor will leave the object in a valid state. Immutable objects must be initialized in a constructor.

Programmers can also use the term constructor to denote one of the tags that wraps data in an algebraic data type. This is a different usage than in this article. For more information, see algebraic data type.

Most languages allow overloading the constructor in that there can be more than one constructor for a class, each having different parameters. Some languages take consideration of some special types of constructors:

Contents

Types of constructors

Parameterized constructors

constructors that can take arguments are termed as parameterized constructors. The number of arguments can be greater or equal to one(1). For example:

class example
{
     int p, q;
   public:
     example(int a, int b);                         //parameterized constructor
};
example :: example(int a, int b)
{
     p = a;
     q = b;
}

When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function. The normal way of object declaration may not work. The constructors can be called explicitly or implicitly.The method of calling the constructor implicitly is also called the shorthand method.

    example e = example(0, 50);                     //explicit call
 
    example e(0, 50);                               //implicit call

Default constructors

Default constructors define the actions to be performed by the compiler when a class object is instantiated without actual parameters. Its sole purpose is to save the data members from the garbage value. It initialize the data members with the default values . [1]

Copy constructors

Copy constructors define the actions performed by the compiler when copying class objects. A copy constructor has one formal parameter that is the type of the class (the parameter may be a reference to an object).

It is used to create a copy of an existing object of the same class. Even though both classes are the same, it counts as a conversion constructor.

Dynamic constructors

Allocation of memory to objects at the time of their construction is known as dynamic construction of objects and such constructors are called as dynamic constructors. This results in saving of memory as it enables the system to allocate the right amount of memory for each object when the objects are not of the same size. The memory is allocated with the help of the new operator. For example,

class String
{
    char *name;
    int length;
 public:
    String()                                     // constructor - 1
    {
       length = 0;
       name = new char[length + 1];             
    }
    String(char *e)
    {
       length strlen(e);                         // constructor - 2
       name = new char[length + 1];              
       strcpy(name, e);
    }
    void join(example &a, example &b);
};
void String :: join(example &a, example &b)
{
    length = a.length + b.length;
    delete name;
    name = new char[length + 1];                 // dynamic allocation    
    strcpy(name, a.name);
    strcat(name, b.name);
};

Conversion constructors

Conversion constructors provide a means for a compiler to implicitly create an object of a class from an object another type. This type of constructor is different from copy constructor because it creates an object from other class. but copy constructor is from the same class.

Constructors syntax

Java

In Java, some of the differences between other methods and constructors are:

Apart from this, a Java constructor performs the following functions in the following order:

  1. It initializes the class variables to default values. (Byte, short, int, long, float, and double variables default to their respective zero values, booleans to false, chars to the null character ('\u0000') and references of any objects to null.)
  2. It then calls the super class constructor (default constructor of super class only if no constructor is defined).
  3. It then initializes the class variables to the specified values like ex: int var = 10; or float var = 10.0f and so on.
  4. It then executes the body of the constructor.

In Java, C#, and VB .NET for reference types the constructor creates objects in a special part of memory called heap. On the other hand the value types (such as int, double etc.), are created in a sequential memory called stack. VB NET and C# allow use of new to create objects of value types. However, in those languages even use of new for value types creates objects only on stack. In C++ when constructor is invoked without new the objects are created on stack. On the other hand when objects are created using new they are created on heap which must be deleted implicitly by a destructor or explicitly by a call to operator delete.

Most languages provides a default constructor if programmer provides no constructor. However, this language provided constructor is taken away as soon as programmer provides any constructor in the class code. In C++ a default constructor is REQUIRED if an array of class objects is to be created. Other languages (Java, C#, VB .NET) have no such restriction.

In C++ copy constructor is called implicitly when class objects are returned from a method by return mechanism or when class objects are passed by value to a function. C++ provides a copy constructor if programmer provides no constructor at all. That is taken away as soon as any constructor is provided by the programmer. C++ provided copy constructor ONLY makes member-wise copy or shallow copies. For deep copies a programmer written copy constructor that makes deep copies will be required. Generally a rule of three is observed. For a class that should have a copy constructor to make deep copies, the three below must be provided. 1. Copy constructor 2. Overloading of assignment operator. 3. A destructor. The above is called rule of three in C++. If cloning of objects is not desired in C++ then copy constructor must be declared private.

Example

public class Example 
{
  //definition of the constructor. 
  public Example()
  {
    this(1);
  }
 
  //overloading a constructor
  public Example(int input)
  {
    data = input; //This is an assignment
  }
 
  //declaration of instance variable(s).
  private int data;
}
//code somewhere else
//instantiating an object with the above constructor
Example e = new Example(42);

Visual Basic .NET

In Visual Basic .NET, constructors use a method declaration with the name "New".

Example

Class Foobar
  Private strData As String
 
  ' Constructor
  Public Sub New(ByVal someParam As String)
     strData = someParam
  End Sub
End Class
' code somewhere else
' instantiating an object with the above constructor
Dim foo As New Foobar(".NET")

C#

In C#, a constructor is thus.

Example

public class MyClass
{
  private int a;
  private string b;
 
  //constructor
  public MyClass() : this(42, "string")
  {
  } 
 
  //overloading a constructor
  public MyClass(int a, string b)
  {
    this.a = a;
    this.b = b;
  }
}
//code somewhere
//instantiating an object with the constructor above
MyClass c = new MyClass(42, "string");

C# static constructor

In C#, a static constructor is a static data initializer. Static constructors allow complex static variable initialization.[3] Static constructors can be called once and call is made implicitly by the run-time right before the first time the class is accessed. Any call to a class (static or constructor call), triggers the static constructor execution. Static constructors are thread safe and are a great way to implement a singleton pattern. When used in a generic programming class, static constructors are called on every new generic instantiation one per type (static variables are instantiated as well).

Example

public class MyClass
{
  private static int _A;
 
  //normal constructor
  static MyClass()
  {
    _A = 32;
  }
 
  //standard default constructor
  public MyClass()
  {
 
  }
}
//code somewhere
//instantiating an object with the constructor above
//right before the instantiation
//the variable static constructor is executed and _A is 32
MyClass c = new MyClass();

C++

In C++, the name of the constructor is the name of the class. It does not return anything. It can have parameters, like any member functions (methods). Constructor functions should be declared in the public section.

The constructor has two parts. First is the initializer list which comes after the parameter list and before the opening curly bracket of the method's body. It starts with a colon and separated by commas. You are not always required to have initializer list, but it gives the opportunity to construct data members with parameters so you can save time (one construction instead of a construction and an assignment). Sometimes you must have initializer list for example if you have const or reference type data members, or members that cannot be default constructed (they don't have parameterless constructor). The order of the list should be the order of the declaration of the data members, because the execution order is that. The second part is the body which is a normal method body surrounded by curly brackets.

C++ allows more than one constructor. The other constructors cannot be called, but can have default values for the parameters. The constructor of a base class (or base classes) can also be called by a derived class. Constructor functions cannot be inherited and their addresses cannot be referred. When memory allocation is required, the operators new and delete are called implicitly.

A copy constructor has a parameter of the same type passed as const reference, for example Vector(const Vector& rhs). If it is not implemented by hand the compiler gives a default implementation which uses the copy constructor for each member variable or simply copies values in case of primitive types. The default implementation is not efficient if the class has dynamically allocated members (or handles to other resources), because it can lead to double calls to delete (or double release of resources) upon destruction.

Example

class Foobar {
public:
    Foobar(double r = 1.0, double alpha = 0.0) // Constructor, parameters with default values.
    : x(r*cos(alpha)) // <- Initializer list
    {
        y = r*sin(alpha); // <- Normal assignment
    }
    // Other member functions
private:
    double x; // Data members, they should be private
    double y;
};

Example invocations:

Foobar a,
       b(3),
       c(5, M_PI/4);

You can write a private data member function at the top section before writing public specifier. If you no longer have access to a constructor then you can use the destructor.

Failure

A constructor that cannot create a valid value should throw an exception. This is because exceptions should be thrown when post-conditions cannot be met, and the post-condition of a constructor is the existence of a valid object. An object which throws during its constructor never comes into existence (although some of its member objects might). This affects how one handles errors and special consideration must be given for exceptions emitted by member variables' constructors[1].

F#

In F#, a constructor can include any let or do statements defined in a class. let statements define private fields and do statements execute code. Additional constructors can be defined using the new keyword.

Example

type MyClass(_a : int, _b : string) = class
    // primary constructor
    let a = _a
    let b = _b
    do printfn "a = %i, b = %s" a b
 
    // additional constructors
    new(_a : int) = MyClass(_a, "") then
        printfn "Integer parameter given"
 
    new(_b : string) = MyClass(0, _b) then
        printfn "String parameter given"
 
    new() = MyClass(0, "") then
        printfn "No parameter given"
end
//code somewhere
//instantiating an object with the primary constructor
let c1 = new MyClass(42, "string")
 
//instantiating an object with additional constructors
let c2 = new MyClass(42)
let c3 = new MyClass("string")
let c4 = MyClass() // "new" keyword is optional

Eiffel

In Eiffel, the routines which initialize new objects are called creation procedures. They are similar to constructors in some ways and different in others. Creation procedures have the following traits:

Although object creation involves some subtleties,[Note 3] the creation of an attribute with a typical declaration x: T as expressed in a creation instruction create x.make consists of the following sequence of steps:

Example

In the first snippet below, class POINT is defined. The procedure make is coded after the keyword feature.

The keyword create introduces a list of procedures which can be used to initialize instances. In this case the list includes default_create, a procedure with an empty implementation inherited from class ANY, and the make procedure coded within the class.

class
    POINT
create
    default_create, make
 
feature
 
    make (a_x_value: REAL; a_y_value: REAL)
        do
            x := a_x_value
            y := a_y_value
        end
 
    x: REAL
            -- X coordinate
 
    y: REAL
            -- Y coordinate
        ...

In the second snippet, a class which is a client to POINT has a declarations my_point_1 and my_point_2 of type POINT.

In procedural code, my_point_1 is created as the origin (0.0, 0.0). Because no creation procedure is specified, the procedure default_create inherited from class ANY is used. This line could have been coded create my_point_1.default_create . Only procedures named as creation procedures can be used in an instruction with the create keyword. Next is a creation instruction for my_point_2, providing initial values for the my_point_2's coordinates. The third instruction makes an ordinary instance call to the make procedure to reinitialize the instance attached to my_point_2 with different values.

    my_point_1: POINT
    my_point_2: POINT
        ...
 
            create my_point_1
            create my_point_2.make (3.0, 4.0)
            my_point_2.make (5.0, 8.0)
        ...

ColdFusion

ColdFusion has no constructor method. Developers using it commonly create an 'init' method that acts as a pseudo-constructor.

Example

<cfcomponent displayname="Cheese">
   <!--- properties --->
   <cfset variables.cheeseName = "" />
   <!--- pseudo-constructor --->
   <cffunction name="init" returntype="Cheese">
      <cfargument name="cheeseName" type="string" required="true" />
      <cfset variables.cheeseName = arguments.cheeseName />
      <cfreturn this />
   </cffunction>
</cfcomponent>

Pascal

In Object Pascal, the constructor is similar to a factory method. The only syntactic difference to regular methods is the keyword constructor in front of the name (instead of procedure or function). It can have any name, though the convention is to have Create as prefix, such as in CreateWithFormatting. Creating an instance of a class works like calling a static method of a class: TPerson.Create("Peter").

Example

program Program;
 
interface
 
type 
  TPerson = class
  private
    FName: string;
  public
    property Name: string read FName; 
    constructor Create(AName: string);
  end;
 
implementation
 
constructor TPerson.Create(AName: string);
begin
  FName := AName;
end;
 
var
  Person: TPerson;
begin
  Person := TPerson.Create("Peter"); // allocates an instance of TPerson and then calls TPerson.Create with the parameter AName = "Peter"
end;

Perl

In Perl version 5, by default, constructors must provide code to create the object (a reference, usually a hash reference, but sometimes an array reference, scalar reference or code reference) and bless it into the correct class. By convention the constructor is named new, but it is not required, or required to be the only one. For example, a Person class may have a constructor named new as well as a constructor new_from_file which reads a file for Person attributes, and new_from_person which uses another Person object as a template.

Example

package Person;
use strict;
use warnings;
 
# constructor
sub new {
	# class name is passed in as 0th
	# argument
	my $class = shift;
	# check if the arguments to the
	# constructor are key => value pairs
	die "$class needs arguments as key => value pairs"
		unless (@_ % 2 == 0);
	# default arguments
	my %defaults; 
 
	# create object as combination of default
	# values and arguments passed
	my $obj = { 
		%defaults,
		@_,
	};
	# check for required arguments
	die "Need first_name and last_name for Person"
		unless ($obj->{first_name} and $obj->{last_name}); 
        # any custom checks of data
        if ($obj->{age} && $obj->{age} < 18)) { # no under-18s
                die "No under-18 Persons";
        }
	# return object blessed into Person class
	bless $obj, $class;
}
1;

Perl with Moose

With the Moose object system for Perl, most of this boilerplate can be left out, a default new is created, attributes can be specified, as well as whether they can be set, reset, or are required. In addition, any extra constructor functionality can be included in a BUILD method which the Moose generated constructor will call, after it has checked the arguments. A BUILDARGS method can be specified to handle constructor arguments not in hashref / key => value form.

Example

package Person;
# enable Moose-style object construction
use Moose; 
 
# first name ( a string) can only be set at construction time ('ro')
has first_name => (is => 'ro', isa => 'Str', required => 1);
# last name ( a string) can only be set at construction time ('ro')
has last_name  => (is => 'ro', isa => 'Str', required => 1);
# age (Integer) can be modified after construction ('rw'), and is not required 
# to be passed to be constructor.  Also creates a 'has_age' method which returns
# true if age has been set
has age        => (is => 'rw', isa => 'Int', predicate => 'has_age');
 
# Check custom requirements
sub BUILD {
      my $self = shift;
      if ($self->has_age && $self->age < 18) { # no under 18s
           die "No under-18 Persons";
      }
}
1;

In both cases the Person class is instiated like this:

use Person;
my $p = Person->new( first_name => 'Sam', last_name => 'Ashe', age => 42 );

PHP

In PHP (version 5 and above), the constructor is a method named __construct(), which the keyword new automatically calls after creating the object. It is usually used to automatically perform various initializations such as property initializations. Constructors can also accept arguments, in which case, when the new statement is written, you also need to send the constructor the function parameters in between the parentheses.[2]

Example

class Person
{
   private $name;
 
   function __construct($name)
   {
       $this->name = $name;
   }
 
   function getName()
   {
       return $this->name;
   }
}

However, constructor in PHP version 4 (and earlier) is a method in a class with the same name of the class. In PHP 5 for reasons of backwards compatibility with PHP 4, when method called __construct is not found, a method with the same name as the class will be called instead. Since PHP 5.3.3 this fallback mechanism will only work for non-namespaced classes.[2]

class Person
{
   private $name;
 
   function Person($name)
   {
       $this->name = $name;
   }
 
   function getName()
   {
       return $this->name;
   }
}

Python

In Python, constructors are created by defining an __new__ method, and are called when a new instance is created by calling the class. Unlike other languages such as C++, derived classes in Python do not call their base classes' constructors. However, when a constructor is not defined, the next one found in the class's Method Resolution Order will be called. Due to Python's use of duck typing, class members are often defined in the constructor, rather than in the class definition itself.

In case of the initial values (not methods) are needed, the __init__ method can be defined.

Example

class ExampleClass(object):
    def __new__(self):
        # We override the constructor to return none instead.
        return None
 
exampleInstance = ExampleClass()
print exampleInstance
None

Constructors simplified, with pseudocode

Constructors are always part of the implementation of classes. A class (in programming) refers to a specification of the general traits of the set of objects that are members of the class rather than the specific traits of any object at all. A simple analogy in pseudocode follows. Consider the set (or class, using its generic meaning) of students at some school. Thus we have

class Student {
    // refers to the class of students
    // ... more omitted ...
}

However, the class Student just provides a generic prototype of what a student should be. To use it, the programmer creates each student as an object or instance of the class. This object is a real quantity of data in memory whose size, layout, traits, and (to some extent) behavior are determined by the class definition. The usual way of creating objects is to call a constructor (classes may in general have many independent constructors). For example,

class Student {
    Student (String studentName, String Address, int ID) {
        // ... storage of input data and other internal fields here ...
    }
    // ...
}

See also

Notes

  1. ^ Eiffel routines are either procedures or functions. Procedures never have a return type. Functions always have a return type.
  2. ^ Because the inherited class invariant must be satisfied, there is no mandatory call to the parents' constructors.
  3. ^ Full specification is documented in the Eiffel ISO/ECMA specification document, available online.[4]
  4. ^ The Eiffel standard requires fields to be initialized on first access, so it is not necessary to perform default field initialization during object creation.

References

  1. ^ Hafiz Sohair Ahmad BCSF10A011 PUNJAB UNIVERSITY PAKISTAN
  2. ^ a b c Constructors and Destructors, from PHP online documentation
  3. ^ Static Constructor in C# on MSDN
  4. ^ Eiffel ISO/ECMA specification document